﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp5
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // 设置闹钟时间为当前时间+10秒
            DateTime alarmTime = DateTime.Now.AddSeconds(10);

            var alarmClock = new AlarmClock(alarmTime);
            alarmClock.Tick += (sender, e) =>
            {
                Console.WriteLine($"[{e.CurrentTime:HH:mm:ss}] {e.Message}");
            };
            alarmClock.Alarm += (sender, e) =>
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine($"[{e.CurrentTime:HH:mm:ss}] {e.Message}");
                Console.ResetColor();
            };
            alarmClock.Start();

            Console.WriteLine("按任意键退出...");
            Console.ReadKey();
        }
    }
    // 闹钟事件参数类
    public class AlarmEventArgs : EventArgs
    {
        public DateTime CurrentTime { get; set; }
        public string Message { get; set; }

        public AlarmEventArgs(DateTime time, string message)
        {
            CurrentTime = time;
            Message = message;
        }
    }

    // 闹钟类
    public class AlarmClock
    {
        // 定义嘀嗒事件和响铃事件
        public event EventHandler<AlarmEventArgs> Tick;
        public event EventHandler<AlarmEventArgs> Alarm;

        public DateTime AlarmTime { get; set; }
        public bool IsRunning { get; private set; }

        public AlarmClock(DateTime alarmTime)
        {
            AlarmTime = alarmTime;
        }

        // 启动闹钟
        public void Start()
        {
            if (IsRunning) return;

            IsRunning = true;
            Console.WriteLine($"闹钟已启动，将在 {AlarmTime:HH:mm:ss} 响铃");

            while (IsRunning)
            {
                DateTime now = DateTime.Now;

                // 触发Tick事件
                OnTick(new AlarmEventArgs(now, "嘀嗒"));

                // 检查是否到达闹铃时间
                if (now >= AlarmTime)
                {
                    // 触发Alarm事件
                    OnAlarm(new AlarmEventArgs(now, "铃铃铃! 时间到了!"));
                    Stop(); // 响铃后自动停止
                }

                Thread.Sleep(1000); // 每秒触发一次
            }
        }

        // 停止闹钟
        public void Stop()
        {
            IsRunning = false;
            Console.WriteLine("闹钟已停止");
        }

        // 触发Tick事件的保护方法
        protected virtual void OnTick(AlarmEventArgs e)
        {
            Tick?.Invoke(this, e);
        }

        // 触发Alarm事件的保护方法
        protected virtual void OnAlarm(AlarmEventArgs e)
        {
            Alarm?.Invoke(this, e);
        }
    }
}
